var express = require('express');
var router = express.Router();
var db = require('../../../tools/database')
function getSS(settings) {
    let toSearch = true;
    let toRange = true;

    var search = settings.search
    var sort = settings.sort
    var min = settings.min
    var max = settings.max
    var loadStart = parseInt(settings.loadStart)
    var loadLimit = parseInt(settings.loadLimit)

    if (search == 'null') { toSearch = false }
    if (min == 0 && max == 999999) { toRange = false }

    switch (sort) {
        case 'price_up': sortCode = 'ItemPrice ASC'; break;
        case 'price_down': sortCode = 'ItemPrice DESC'; break;
        case 'date_down': sortCode = 'ItemID DESC'; break;
    }

    var sql, options

    if (!toSearch && !toRange) {
        sql = `SELECT * FROM Items ORDER BY ${sortCode} LIMIT ?,?;`
        options = [loadStart, loadLimit]

    } else if (toSearch && !toRange) {
        sql = `SELECT * FROM Items WHERE ItemName LIKE ? ORDER BY ${sortCode} LIMIT ?,?;`
        options = [`%${search}%`, loadStart, loadLimit]

    } else if (!toSearch && toRange) {
        sql = `SELECT * FROM Items WHERE ItemPrice BETWEEN ? AND ? ORDER BY ${sortCode} LIMIT ?,?;`
        options = [min, max, loadStart, loadLimit]

    } else if (toSearch && toRange) {
        sql = sql = `SELECT * FROM Items WHERE ItemName LIKE ? AND ItemPrice BETWEEN ? AND ? ORDER BY ${sortCode} LIMIT ?,?;`
        options = [`%${search}%`, min, max, loadStart, loadLimit]

    }
    return [sql, options]
}

// get itemSet according to the settings
router.use(function (req, res, next) {
    [sql, options] = getSS(req.query)
    db.queryRespond(sql, options, res, false, false)
});


module.exports = router;